package com.netty.cn.rpc.protoc;

import com.netty.cn.rpc.protoc.model.ClientModel;
import com.netty.cn.rpc.protoc.server.ProtocServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * 
 * @author wangzonghui
 * @date 2021-07-19 16:36:36
 * @Description proto类型netty服务端
 */
public class RpcProtocServer {

	public static void main(String[] args) {
		try {
			EventLoopGroup group = new NioEventLoopGroup();
			EventLoopGroup workGroup = new NioEventLoopGroup(4);
			try {
			    ServerBootstrap b = new ServerBootstrap();
			    b.group(group,workGroup)
			    .channel(NioServerSocketChannel.class)
			    .childHandler(new ChannelInitializer<SocketChannel>() {
			    	
			        @Override
			        protected void initChannel(SocketChannel ch) throws Exception {
			            
			        	ChannelPipeline channelPipeline = ch.pipeline();
			        	//解码
			        	channelPipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
			            .addLast("protobufDecoder",new ProtobufDecoder(ClientModel.ClientDataModel.getDefaultInstance()))  
			            //编码规则
			            .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
			            .addLast("protobufEncoder", new ProtobufEncoder())  
			            // ----Protobuf处理器END----  
			            .addLast(new ProtocServerHandler());
			        }
			    });
			    ChannelFuture f = b.bind("localhost",9090).sync();
			    f.channel().closeFuture().sync();
			} finally {
				group.shutdownGracefully().sync();
				workGroup.shutdownGracefully().sync();
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
